<!--
 * @Author: fanyaqing
 * @Date: 2021-08-09 14:24:28
 * @LastEditTime: 2021-08-16 17:14:03
 * @LastEditors: fanyaqing
 * @Description: 
 * @FilePath: \supermall\src\views\detail\detail.vue
-->
<template>
  <div id="detail">
    <detail-nav-bar ref="navBar" @titleClick="titleClick"></detail-nav-bar>
    <scroll
      class="content"
      ref="scroll"
      :probeType="3"
      @scrollPosition="scrollPosition"
    >
      <detail-swiper :topImages="topImages"></detail-swiper>
      <!-- 属性：topImages，传入值最好写成：top-images这种形式,在内部不区分大小写，不过在cli3中解决了这个问题 -->
      <detail-base-info :goods="goods"></detail-base-info>
      <detail-shop-info :shop="shop"></detail-shop-info>
      <detail-goods-info
        :detailInfo="detailInfo"
        @imageLoad="imageLoad"
      ></detail-goods-info>
      <detail-param-info ref="param" :paramInfo="paramInfo"></detail-param-info>
      <detail-comment-info ref="comment" :commentInfo="commentInfo"></detail-comment-info>
      <goods-list ref="recommend" :goods="recommends"></goods-list>
    </scroll>
    <detail-bottom-bar @addToCart="addToCart"></detail-bottom-bar>

    <back-top v-show="backTopShow" @click.native="backClick"></back-top>
  </div>
</template>
<script>
import DetailNavBar from './childComponents/detailNavBar';
import DetailSwiper from './childComponents/detailSwiper';
import DetailBaseInfo from './childComponents/DetailBaseInfo';
import DetailShopInfo from './childComponents/DetailShopInfo';
import DetailGoodsInfo from './childComponents/DetailGoodsInfo';
import DetailParamInfo from './childComponents/DetailParamInfo';
import DetailCommentInfo from './childComponents/DetailCommentInfo';
import DetailBottomBar from './childComponents/detailBottomBar';
import Scroll from 'components/common/scroll/Scroll'
import GoodsList from 'components/content/goods/GoodsList'

import shopLogoImg from 'assets/img/common/logo.jpg'
import placeholder from 'assets/img/common/placeholder.png';

import {getDetail,Goods,Shop,GoodsParam,getRecommend} from 'network/detail'
import {getHomeMultidata} from 'network/home'

import {itemListenerMixin,backTopMixin} from 'common/mixin'
import {mapActions} from 'vuex'

export default {
  components:{
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    DetailBottomBar,
    Scroll,
    GoodsList
  },
  mixins:[itemListenerMixin,backTopMixin],
  data() {
    return {
      id:'',
      topImages:[],
      goods:{},
      shop:{},
      detailInfo:{},
      paramInfo:{},
      commentInfo:{},
      recommends:[],
      themeTopYs:[0],//头部导航，点击滚动到对应的位置
    }
  },
  created(){
    // 1.保存传入的id,这个只执行了一次,因为设置了keep-alive
    // this.id=this.$route.params.id;
    // console.log(this.id)
    // 2.根据id请求详情数据
    // this.getDetail()
  },
  mounted() {
    
  },
  activated() {
    this.id=this.$route.params.id;
    this.getDetail()
  },
  deactivated(){
    // 当前组件关闭时，将事件总线销毁，防止和其他同名的事件总线相互影响
    this.$bus.$off('imageLoaded',this.itemImgListener)
  },
  // destroyed() {
  //  这段代码，是当时视频的deavtivated事件没有触发可能是脚手架版本的问题，目前可以使用
  //   // 当前组件关闭时，将事件总线销毁，防止和其他同名的事件总线相互影响
  //   this.$bus.$off('imageLoaded',this.itemImgListener)
  // },
  methods:{
    ...mapActions(['addCart']),
    /*
      网络请求接口
    */ 
    getDetail(){
      // 网络请求接口
      // getDetail(this.id).then(res=>{
      //   console.log(res)
          // // 1.获取顶部的图片轮播数据
          // const data=res.result
          // this.topImages=data.itemInfo.topImages
          // // 2.获取商品信息
          // this.goods=new Goods(data.itemInfo,data.columns,data.shopInfo.services)
          // // 3.获取店铺信息
          // this.shop=new Shop(data.shopInfo)
          // // 4.获取详情信息
            // this.detailInfo=data.detailInfo
            // // 5.商品的参数信息
            // this.paramInfo=new GoodsParam(data.itemParams.info,data.itemParams.rule)
            // // 6.取出评论的信息
            // if(data.rate.cRate!==0){
            //   this.commentInfo=data.rate.list[0]
            // }
      // })
      // 请求推荐数据
      // getRecommend().then(res=>{
      //   this.recommends=res.data.list
      // })
      /*
        获取各个组件的offsetTop，来实现点击导航跳转到对应的位置。
        1.第一次获取，值不对
        值不对的原因：this.$refs.params.$el组件没有渲染出来
          this.themeTopYs=[0];
          this.themeTopYs.push(this.$refs.param.$el.offsetTop)
          this.themeTopYs.push(this.$refs.comment.$el.offsetTop)
          this.themeTopYs.push(this.$refs.recommend.$el.offsetTop)
        2.第二次获取使用nextTick方法，组件数据加载完之后执行这个方法，根据最新数据，对应的dom是已经被渲染出来
        但是图片依然是没有加载完（目前获取到offsetTop不包含先前的图片
        offseTop值不对的时候，都是因为图片的问题
        this.$nextTick(()=>{
          this.themeTopYs=[0];
          this.themeTopYs.push(this.$refs.param.$el.offsetTop)
          this.themeTopYs.push(this.$refs.comment.$el.offsetTop)
          this.themeTopYs.push(this.$refs.recommend.$el.offsetTop)
        })
      */ 
      // 模拟接口
      getHomeMultidata().then(res=>{
        this.topImages=res.data.banner.list;

        const itemInfo={
          title:'2021春秋季新款原宿风长袖T恤女bf潮学生韩版拼接白色复古港味宽松百搭上衣打底',
          desc:'新款上市',
          price:'￥38.50',
          oldPrice:'￥69.50',
          discountDesc:'活动价',
          lowNowPrice:'38.50'
        }
        const columns=[
          "销量 1580",
          "收藏33人",
          "默认快递"
        ]
        const services=[]
        // 2.获取商品信息
        this.goods=new Goods(itemInfo,columns,services)

        const shopInfo={
          shopLogo:shopLogoImg,
          name:'仲陌美',
          cFans:17145,
          cSells:57876,
          score:[
            {isBetter:false,name:"描述相符",score:4.64},
            {isBetter:true,name:"价格合理",score:5},
            {isBetter:false,name:"质量满意",score:4.62}
          ],
          cGoods:99
        }
        // 3.获取店铺信息
        this.shop=new Shop(shopInfo)
        // 4.获取详情信息
        const detailInfo={
          desc:'新款上市~',
          detailImage:[
            {
              anchor:'model_img',
              desc:'',
              key:'穿着效果',
              list:[
                shopLogoImg,
                shopLogoImg,
                shopLogoImg,
              ]
            }
          ]
        }
        this.detailInfo=detailInfo;
        // 5.商品的参数信息
        const info={
          images:'',
          set:[
            {key:'图案',value:'宫廷复古图/民族复古图，字母/文字'},
            {key:'厂名',value:'阿离有限公司'},
            {key:'颜色',value:'红白拼接'},
            {key:'袖型',value:'红白拼接'},
            {key:'上衣厚度',value:'红白拼接'},
            {key:'尺码',value:'xl，l，m，xxl'},
            {key:'颜色',value:'红白拼接'},
            {key:'颜色',value:'红白拼接'},
            {key:'颜色',value:'红白拼接'},
            {key:'颜色',value:'红白拼接'},
          ]
        }
        const rule={
          tables:[
            [
              ['尺码','m','l','xl','xxl'],
              ['衣长','m','l','xl','xxl'],
              ['胸围','m','l','xl','xxl'],
              ['袖长','m','l','xl','xxl'],
            ]
          ]
        }
        this.paramInfo=new GoodsParam(info,rule)
        // 6.取出评论的信息
        const commentInfo={
          cRate:125,
          list:[
            {
              user:{avatar:shopLogoImg,uname:'小舞'},
              content:'好好好好好好好好好好好好好好好好好好好好',
              created:1535694719,
              style:'颜色：红白；尺码：m',
              images:[shopLogoImg]
            }
          ]
        }
        if(commentInfo.cRate!==0){
          this.commentInfo=commentInfo.list[0];
        }
      })
      // 模拟接口，请求推荐数据
      let tempArray=[
        {show:{img:placeholder},id:'id1',price:'100.00',cfav:20,title:'这是一个商品的标题。'},
        {show:{img:placeholder},id:'id1',price:'100.00',cfav:20,title:'这是一个商品的标题。'},
        {show:{img:placeholder},id:'id1',price:'100.00',cfav:20,title:'这是一个商品的标题。'},
        {show:{img:placeholder},id:'id1',price:'100.00',cfav:20,title:'这是一个商品的标题。'},
        {show:{img:placeholder},id:'id1',price:'100.00',cfav:20,title:'这是一个商品的标题。'},

      ];
      this.recommends=tempArray;
    },
    /*
    事件监听
    */ 
    imageLoad(){
      this.$refs.scroll.refresh()

      // 图片加载完成后，再获取各个组件对应的offsetTop
      this.themeTopYs=[0];
      this.themeTopYs.push(this.$refs.param.$el.offsetTop)
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop)
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop)
      
    },
    titleClick(index){
      this.$refs.scroll.scrollTop(0,-this.themeTopYs[index])
    },
    scrollPosition(position){
      /*第一种做法*/ 
      // 1.获取滚动的y值
      const positionY=-position.y;
          // this.$refs.navBar.currentIndex=index;
      // 2.将positionY和主题中值进行对比
      // [0,500,1500,2000]
      // positionY在0到500，index=0
      // positionY在500到1000，index=1
      // positionY在1000到1500，index=2
      // positionY在2000以外，index=3

      this.themeTopYs.forEach((res,index)=>{
        // console.log(res)
          if(positionY>=this.themeTopYs[3]){
            // positionY在2000以外，index=3
            this.$refs.navBar.currentIndex=3;
          }
          if(positionY>=this.themeTopYs[index]&&positionY<this.themeTopYs[index+1]){
            // positionY在0到500，index=0
            // positionY在500到1000，index=1
            // positionY在1000到1500，index=2
            this.$refs.navBar.currentIndex=index;
            
          }
        
      })
      /*第二种做法
        在this.themeTopYs后面添加一个最大值Number.MAX_VALUE，循环的时候for，length-1，
        然后只需要，positionY>=this.themeTopYs[index]&&positionY<this.themeTopYs[index+1]
      */ 

      // 返回头部
      this.listenShowBackTop(position);
    },
    addToCart(){
      // 1.获取购物车需要展示的信息
      const product={};
      product.image=this.topImages[0].image;
      product.title=this.goods.title;
      product.desc=this.goods.desc;
      product.price=this.goods.realPrice;
      product.iid=this.id;

      // 2.将商品添加到购物车里
      // this.$store.dispatch('addCart',product).then(res=>{
      //   console.log(res)
      // })
      this.addCart(product).then(res=>{
        console.log(res,'......')
        this.$toast.show(res)
      })
    }
  }
}
</script>
<style scoped>
  #detail{
    height: 100vh;
    position: relative;
    z-index: 5;
    background-color: #fff;
  }
  .content{
    position: absolute;
    top: 44px;
    right: 0;
    left: 0;
    bottom: 58px;

    overflow: hidden;
  }
</style>